package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.CheckRange;
import com.sky.utils.WeChatPayUtil;
import com.sky.utils.ride.RideCheck;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
//
    // //组装订单表orders的数据,保存
    // Orders orders = new Orders();
    // // BeanUtils.copyProperties(dto,orders);
    // //订单号
    // orders.setNumber(String.valueOf(System.currentTimeMillis()));
    // //订单状态
    // orders.setStatus(Orders.PENDING_PAYMENT);
    // //用户id
    // orders.setUserId(BaseContext.getCurrentId());
    // //地址id
    // orders.setAddressBookId(dto.getAddressBookId());
    // //下单时间
    // orders.setOrderTime(LocalDateTime.now());
    // //支付状态
    // orders.setPayStatus(Orders.UN_PAID);
    // //备注
    // orders.setRemark(dto.getRemark());
    // //手机号
    // orders.setPhone(addressBook.getPhone());
    // //地址
    // orders.setAddress(addressBook.getDetail());
    // //收货人
    // orders.setConsignee(addressBook.getConsignee());
    // //打包费
    // orders.setPackAmount(dto.getPackAmount());
    // //餐具数量
    // orders.setTablewareNumber(dto.getTablewareNumber());
    // //餐具数量状态
    // orders.setTablewareStatus(dto.getTablewareStatus());
    // //支付方式 1代表微信支付
    // orders.setPayMethod(1);
    // //配送状态  1立即送出  0选择具体时间
    // orders.setDeliveryStatus(dto.getDeliveryStatus());
    // //实收金额
    // orders.setAmount(dto.getAmount());
    // //预计送达时间
    // orders.setEstimatedDeliveryTime(dto.getEstimatedDeliveryTime());

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private CheckRange checkRange;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    // public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
    //     // 当前登录用户id
    //     Long userId = BaseContext.getCurrentId();
    //     //getById()需要自己实现
    //     User user = userMapper.getById(userId);
    //
    //     //调用微信支付接口，生成预支付交易单
    //     JSONObject jsonObject = weChatPayUtil.pay(
    //             ordersPaymentDTO.getOrderNumber(), //商户订单号
    //             new BigDecimal(0.01), //支付金额，单位 元
    //             "苍穹外卖订单", //商品描述
    //             user.getOpenid() //微信用户的openid
    //     );
    //
    //     if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
    //         throw new OrderBusinessException("该订单已支付");
    //     }
    //
    //     OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
    //     vo.setPackageStr(jsonObject.getString("package"));
    //
    //     return vo;
    // }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    @Override
    public PageResult getHistoryOrdersByPage(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        dto.setUserId(BaseContext.getCurrentId());
        Page<Orders> orders = orderMapper.getOrdersByUserId(dto);
        List<OrderVO> arrayList = new ArrayList<>();
        if (orders != null && !orders.isEmpty()) {
            for (Orders order : orders) {
                Long orderId = order.getId();
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order,orderVO);
                orderVO.setOrderDetailList(orderDetails);
                arrayList.add(orderVO);
            }
        }
        return new PageResult(orders.getTotal(),arrayList);
    }

    @Override
    public OrderVO getOrderDetail(Long id) {
        OrderVO orderVO = orderMapper.getOrderByOrderId(id);
        orderVO.setOrderDetailList(orderDetailMapper.getByOrderId(id));
        return orderVO;
    }

    @Override
    public void cancelOrder(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(6); //已取消
        orderMapper.cancelOrder(id);
    }

    //将当前订单详情数据添加到购物车，插入到数据库
    @Override
    public void repetition(Long id) {
        //根据订单id查询所属订单详情数据
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        if (orderDetails == null || orderDetails.size() == 0) {
            throw new OrderBusinessException(MessageConstant.ORDER_DETAIL_IS_NULL);
        }
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        //组装购物车表的数据，保存
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());

            shoppingCarts.add(shoppingCart);
        }
        //批量保存购物车的数据源
        shoppingCartMapper.insertBatch(shoppingCarts);

    }

    /**
     * 管理端用户搜索
     * @param dto
     * @return
     */
    @Override
    public PageResult search(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<Orders> orders = orderMapper.getByPage(dto);

        List<OrderVO> list = new ArrayList<>();
        for (Orders order : orders) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order,orderVO);
            Long orderId = order.getId();

            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
            List<String> stringList = orderDetails.stream().map(orderDetail ->
                    orderDetail.getName() + "*" + orderDetail.getNumber()).collect(Collectors.toList());

            orderVO.setOrderDishes(String.join(";", stringList));
            list.add(orderVO);
        }

        return new PageResult(orders.getTotal(),list);
    }

    @Override
    public OrderStatisticsVO countStatus() {
        Integer confirmed = orderMapper.countStatus(3);
        Integer deliveryInProgress = orderMapper.countStatus(4);
        Integer toBeConfirmed = orderMapper.countStatus(2);
        OrderStatisticsVO build = OrderStatisticsVO.builder().confirmed(confirmed).deliveryInProgress(deliveryInProgress).toBeConfirmed(toBeConfirmed).build();
        return build;
    }

    @Override
    public OrderVO getDetails(Long id) {
        OrderVO order = orderMapper.getOrderByOrderId(id);
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        List<Dish> dishList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            Long dishId = orderDetail.getDishId();
            Dish dish = dishMapper.getDishById(dishId);
            dishList.add(dish);
        }
        String orderDishes = JSONObject.toJSONString(dishList);
        order.setOrderDishes(orderDishes);
        return order;
    }

    @Override
    public void cancelOrderByDto(OrdersCancelDTO dto) {
        Orders orders = new Orders();
        orders.setId(dto.getId());
        orders.setStatus(6); //已取消
        orders.setCancelReason(dto.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.cancelOrderByDto(orders);
    }

    @Override
    public void delivery(Long id) {
        Orders order = new Orders();
        order.setId(id);
        order.setStatus(4);
        order.setEstimatedDeliveryTime(LocalDateTime.now().plusMinutes(30));
        order.setDeliveryStatus(1);
        orderMapper.update(order);
    }

    @Override
    public void confirm(OrdersConfirmDTO dto) {
        Orders order = new Orders();
        BeanUtils.copyProperties(dto,order);
        order.setStatus(3);
        orderMapper.confirm(order);
    }

    @Override
    public void rejection(OrdersRejectionDTO dto) {
        //只有待接单的可以拒单
        // OrderVO order = orderMapper.getOrderByOrderId(dto.getId());
        // if (order.getStatus() == null || order.getStatus() != 2) {
        //     throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        // }

        // //付款了，给用户退钱
        // Integer payStatus = order.getPayStatus();
        // if (payStatus == 1) {
        //     // todo 给用户退钱
        // }

        Orders orders = new Orders();
        BeanUtils.copyProperties(dto,orders);
        orders.setStatus(6);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        OrderVO orderVO = orderMapper.getOrderByOrderId(id);
        Integer status = orderVO.getStatus();
        if (status == null || status != 4) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders build = Orders.builder().id(id).status(5).deliveryTime(LocalDateTime.now()).build();
        orderMapper.update(build);
    }

    /**
     * 用户下单功能
     * @param dto
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        //异常处理的情况（地址为空，购物车为空，超出配送范围）
        AddressBook addressBook = addressBookMapper.findById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //检查是否在配送范围内
        // String userUrl = addressBook.getProvinceName() + addressBook.getCityName()
        //         + addressBook.getDistrictName() + addressBook.getDetail();
        // checkRange.checkRange(userUrl);

        // 改造官方的代码
        String userUrl = addressBook.getProvinceName() + addressBook.getCityName()
                + addressBook.getDistrictName() + addressBook.getDetail();
        try {
            RideCheck.rideCheck(userUrl);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        //根据当前登录用户查询所属的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto,orders);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(BaseContext.getCurrentId());
        //订单状态
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        //支付状态
        orders.setPayStatus(Orders.PAID);
        orders.setOrderTime(LocalDateTime.now());

        orderMapper.insert(orders);

        ArrayList<OrderDetail> orderDetailArrayList = new ArrayList<>();
        //组装订单明细表的数据，保存
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());

            orderDetailArrayList.add(orderDetail);
        }
        //批量保存订单明细数据
        orderDetailMapper.insertBatch(orderDetailArrayList);

        //清空购物车的数据源
        //根据userId清空购物车的数据
        shoppingCartMapper.clean(BaseContext.getCurrentId());

        //组装返回的对象OrderSubmitVo
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());

        /**
         * 跟前端的约定
         * type: 1来单提醒 2催单提醒
         * orderId
         * 订单号：number
         */
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号为"+orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

        return orderSubmitVO;
    }

    @Override
    public void reminder(Long id) {
        OrderVO orders = orderMapper.getOrderByOrderId(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于websocket实现催单
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","订单号为"+orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }


}




























